package com.household.controller.order;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.household.domain.ResponseResult;
import com.household.domain.entity.User;
import com.household.domain.enums.OrderStatusEnum;
import com.household.domain.enums.ResponseErrorCodeEnum;
import com.household.domain.enums.RoleEnum;
import com.household.domain.vo.AdminUserVO;
import com.household.domain.vo.BootstrapTableVO;
import com.household.exception.CustomException;
import com.household.feigns.LoginClient;
import com.household.service.OrdersService;
import com.household.service.UserService;
import com.household.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * Created By wanzhen
 * 2023. 2023/4/6. 11:41
 */
@RestController
@RequestMapping("/admin")
public class OrderController {

    private final OrdersService ordersService;

    private final UserService userService;

    private final LoginClient loginClient;

    @Autowired
    public OrderController(OrdersService ordersService, UserService userService, LoginClient loginClient) {
        this.ordersService = ordersService;
        this.userService = userService;
        this.loginClient = loginClient;
    }

    /**
     * 获取所有订单
     * - 普通用户：userId = self
     * - 配送员：courierId = self
     * - 管理员：无限制
     *
     * @param type 0:正常订单；1：已删除订单
     * @author jitwxs
     * @date 2019/4/24 22:21
     */
    @RequestMapping("/order/list")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_COMPANY') or hasRole('ROLE_ADMIN')")
    public BootstrapTableVO listSelfOrder(@RequestParam(required = false, defaultValue = "1") Integer current,
                                          @RequestParam(required = false, defaultValue = "10") Integer size,
                                          String type, String startDate, String endDate, String status, String id,
                                          @AuthenticationPrincipal User user) {
        Integer isDelete = StringUtils.toInteger(type, -1);
        if (isDelete == -1) {
            throw new CustomException(ResponseErrorCodeEnum.PARAMETER_ERROR);
        }
        String userId = user.getId();
        StringBuilder sql = new StringBuilder();
        OrderStatusEnum orderStatusEnum = OrderStatusEnum.getByStatus(StringUtils.toInteger(status, -1));
//        订单状态
        if (orderStatusEnum != null) {
            sql.append(" AND orders.status = ").append(orderStatusEnum.getStatus());
        }
//      开始时间
        if (StringUtils.isNotBlank(startDate)) {
            sql.append(" AND orders.create_date > '").append(startDate).append("'");
        }

//        截至时间
        if (StringUtils.isNotBlank(endDate)) {
            sql.append(" AND orders.create_date < '").append(endDate).append("'");
        }
//      订单号
        if (!StringUtils.isNotBlank(id)) {
            sql.append(" AND orders.id = ").append(id);
        }

        Page page = new Page<>(current, size);
        page.setOptimizeCountSql(false);
        page.addOrder(new OrderItem("create_date", false));

        switch (user.getRole()) {
            case ADMIN:
                return ordersService.pageAdminOrderVO(page, sql.toString(), isDelete);
            default:
                return new BootstrapTableVO();
        }


    }

    @PostMapping("/order/batch-rollback")
    @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
    public ResponseResult batchRollback(String[] ids, @AuthenticationPrincipal User user) {
        switch (user.getRole()) {
            case ADMIN:
                return ordersService.batchRollback(ids, null);
            default:
                return ResponseResult.failure(ResponseErrorCodeEnum.NO_PERMISSION);
        }
    }



}
